<template>
  <!-- 编辑地址 -->
  <el-dialog
    :title="$t('编辑地址')"
    destroy-on-close
    append-to-body
    :visible.sync="show"
    width="800px"
    :before-close="cancel"
  >
    <el-form :model="form" label-width="120px" ref="formRef" size="small" width="500" :rules="rules">
      <!-- 收货人 -->
      <el-form-item :label="$t('收货人')" prop="receiveName">
        <el-input v-model="form.receiveName" clearable />
      </el-form-item>
      <!-- 收货人电话 -->
      <el-form-item :label="$t('收货人电话')" prop="receivePhone">
        <el-input v-model="form.receivePhone" clearable />
      </el-form-item>
      <!-- 邮编 -->
      <el-form-item :label="$t('邮编')" prop="receivePostcode">
        <el-input v-model="form.receivePostcode" clearable />
      </el-form-item>
      <!-- 地址1（省） -->
      <el-form-item :label="$t('地址1（省）')" prop="address1" style="position: relative; margin-top: 10px">
        <div class="form-item">和区域匹配</div>
        <el-input v-model="form.address1" clearable />
      </el-form-item>
      <!-- 地址2（市）-->
      <el-form-item :label="$t('地址2（市）')" prop="address2">
        <el-input v-model="form.address2" clearable />
      </el-form-item>
      <!-- 地址3（区） -->
      <el-form-item :label="$t('地址3（区）')" prop="address3">
        <el-input v-model="form.address3" clearable />
      </el-form-item>
      <!-- 地址4 -->
      <el-form-item :label="$t('地址4')" prop="address4">
        <el-input v-model="form.address4" clearable />
      </el-form-item>
      <!-- 地址5 -->
      <el-form-item :label="$t('地址5')" prop="address5">
        <el-input v-model="form.address5" clearable />
      </el-form-item>
      <!-- 地址6 -->
      <el-form-item :label="$t('地址6')" prop="address6">
        <el-input v-model="form.address6" clearable />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">
        <!-- 取 消 -->
        {{ $t('取消') }}
      </el-button>
      <el-button @click="handleEditMainOrder" type="primary">
        <!-- 确 认 -->
        {{ $t('确定') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateOrder } from '@/api/distribution/orderBatchs/index'
export default {
  props: {
    formData: {
      type: Object,
      default: () => ({}),
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      form: {
        receiveName: '',
        receivePhone: '',
        receivePostcode: '',
        address1: '',
        address2: '',
        address3: '',
        address4: '',
        address5: '',
        address6: '',
      },
      rules: {
        receiveName: [{ required: true, message: '请输入', trigger: 'blur' }],
        receivePhone: [{ required: true, message: '请输入', trigger: 'blur' }],
        receivePostcode: [{ required: true, message: '请输入', trigger: 'blur' }],
        address1: [
          {
            validator: this.validateCharLength,
            required: true,
            trigger: 'change',
          },
        ],
        address2: [
          {
            validator: this.validateCharLength,
            required: true,
            trigger: 'change',
          },
        ],
        address3: [
          {
            validator: this.validateCharLength,
            required: true,
            trigger: 'change',
          },
        ],
        address4: [
          {
            validator: this.validateCharLength,
            required: false,
            trigger: 'change',
          },
        ],
        address5: [
          {
            validator: this.validateCharLength,
            required: false,
            trigger: 'change',
          },
        ],
        address6: [
          {
            validator: this.validateCharLength,
            required: false,
            trigger: 'change',
          },
        ],
      },
    }
  },
  watch: {
    show: function (newValue) {
      if (newValue) {
        Object.keys(this.formData).forEach((key) => {
          this.form[key] = this.formData[key] || ''
        })
        this.$nextTick(() => {
          this.$refs['formRef'].validate()
        })
      }
    },
  },
  methods: {
    getLength(str) {
      // 先把全角字符转成半角字符
      str = str.replace(/[^\x00-\xff]/g, '**')
      let len = 0
      for (let i = 0; i < str.length; i++) {
        len += 1
      }
      return len
    },

    validateCharLength(rule, value, callback) {
      const { field } = rule
      const strLength = this.getLength(value)
      console.log(`strLength ==>`, JSON.parse(JSON.stringify(strLength)))
      // 24 半角字符
      if (field == 'address2') {
        if (strLength > 24) return callback(new Error('长度不能超过24个半角字符'))
      }

      // 32 半角字符
      if (field == 'address3' || field == 'address4') {
        if (strLength > 32) return callback(new Error('长度不能超过32个半角字符'))
      }

      // 50 半角字符
      if (field == 'address5' || field == 'address6') {
        if (strLength > 50) return callback(new Error('长度不能超过50个半角字符'))
      }
      return callback()
    },
    handleEditMainOrder() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          updateOrder(this.form).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })
              this.$emit('getList')
              this.cancel()
            }
          })
        }
      })
    },
    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style scoped lang="scss">
.form-item {
  position: absolute;
  top: 0;
  top: -22px;
  color: red;
  font-size: 12px;
}
</style>
